package com.igatewebsol.common;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;

public class DAOFactory {
	
	private static Configuration daoConfig;
	// This is a static class. Instances of this class will not be created.
	private DAOFactory() {}
	
	public static Object getDaoImpl(String daoName) 
		{
		// validate and clean input
		if (daoName == null || daoName.trim().equals(""))
			return null;
		else
			daoName = daoName.trim();
		// read the configuration file
		if (daoConfig == null)
			{
			try
				{
				daoConfig = new XMLConfiguration("dao.xml");
				}
			catch (Exception e)
				{
				e.printStackTrace();
				}
			}
		if (daoConfig != null)
			{
			try
				{
				String daoImplClassName = null;
				// loop through all the dao definitions to get to the correct dao name
				List services = ((XMLConfiguration)daoConfig).configurationsAt("dao-mapping");
			if(services != null)
				for(Iterator it = services.iterator(); it.hasNext();)
					{
					HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
					String daoConfigName = sub.getString("daoName");
				if (daoConfigName.equalsIgnoreCase(daoName))
						{
						daoImplClassName = sub.getString("daoImpl");
						
						break;
						}
					}
				if (daoImplClassName != null)
					{
					Object daoImpl = null;
					// create object of DAOImpl class
					try
						{
						daoImpl = Class.forName(daoImplClassName).newInstance();
						}
					catch (Exception cnfe)
						{
						}
					return daoImpl;
					}
				else
					{
					// daoImpl is not configured in the dao.xml file
					return null;
					}
				}
			catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		else
			{
			}
			return null;
		}
	
	public static void main(String args[])
	{
		getDaoImpl(null);
	}
}
